package com.chenjj.java.test.juc.tools;

import com.chenjj.java.juc.tools.countdownlatch.*;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 *
 */
public class CountDownLatchTester {

    @Test
    public void test1() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        AbstractHealthCheckService dataCheckService = new DataHealthCheck(latch);
        AbstractHealthCheckService networkCheckService = new NetworkHealthCheck(latch);

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(dataCheckService);
        executorService.execute(networkCheckService);

        long s = System.currentTimeMillis();
        System.out.println("等待线程执行完毕..");
        latch.await();
        long e = System.currentTimeMillis();
        System.out.println("线程已执行完毕，耗时:"+(e-s)+"ms，服务状态[dataCheckServiceUp:"+dataCheckService.is_serviceUp()+",networkCheckServiceUp:"+networkCheckService.is_serviceUp()+"]");
    }

    /**
     * 测试自己实现的一个countdownlatch -- CountDownLatchSimlpe
     */
    @Test
    public void test2() throws InterruptedException {
        CountDownLatch latch = new CountDownLatchSimlpe(2);
        AbstractHealthCheckService dataCheckService = new DataHealthCheck(latch);
        AbstractHealthCheckService networkCheckService = new NetworkHealthCheck(latch);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(dataCheckService);
        executorService.execute(networkCheckService);

        long s = System.currentTimeMillis();
        System.out.println("等待线程执行完毕..");
        latch.await();
        long e = System.currentTimeMillis();
        System.out.println("线程已执行完毕，耗时:"+(e-s)+"ms，服务状态[dataCheckServiceUp:"+dataCheckService.is_serviceUp()+",networkCheckServiceUp:"+networkCheckService.is_serviceUp()+"]");

    }

    /**
     * 测试自己实现的一个countdownlatch -- CountDownLatchSimlpe1
     */
    @Test
    public void test3() throws InterruptedException {
        CountDownLatch latch = new CountDownLatchSimlpe1(2);
        AbstractHealthCheckService dataCheckService = new DataHealthCheck(latch);
        AbstractHealthCheckService networkCheckService = new NetworkHealthCheck(latch);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(dataCheckService);
        executorService.execute(networkCheckService);

        long s = System.currentTimeMillis();
        System.out.println("等待线程执行完毕..");
        latch.await();
        long e = System.currentTimeMillis();
        System.out.println("线程已执行完毕，耗时:"+(e-s)+"ms，服务状态[dataCheckServiceUp:"+dataCheckService.is_serviceUp()+",networkCheckServiceUp:"+networkCheckService.is_serviceUp()+"]");

    }
}
